package com.oj.controller;

import com.oj.entity.Contest;
import com.oj.entity.ContestProblem;
import com.oj.mapper.ContestMapper;
import com.oj.mapper.ContestProblemMapper;
import com.oj.util.CodeMsg;
import com.oj.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;

@Slf4j
@Controller
@RequestMapping
public class ContestProblemController {
    @Autowired
    private ContestMapper contestMapper;

    @Autowired
    private ContestProblemMapper contestProblemMapper;

    @ResponseBody
    @PostMapping(value = "/api/admin/contest/problem/add")
    public Result addContestProblem(@RequestBody @Validated(value = {ContestProblem.updateValid.class}) ContestProblem contestProblem,
                              HttpServletRequest request, HttpServletResponse response, Model model){
        if (contestProblem.getProblem_id() == null) {
            return Result.error(CodeMsg.PARAM_NULL.locale());
        }
        Contest contest = contestMapper.queryAdmin(contestProblem.getContest_id());
        if (contest == null) {
            return Result.error(CodeMsg.INNER_FAULT.locale());
        }

        int index = 0;
        String[] indexList={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        for (int i = 0; i < 26; i++) {
            if (contestProblemMapper.query(contestProblem.getContest_id(), indexList[i]) == null) {
                index = i;
                break;
            }
        }
        if (index == 26) {
            return Result.error(CodeMsg.INNER_FAULT.locale());
        }

        contestProblem.setNum(indexList[index]);
        if (!contestProblemMapper.insert(contestProblem)) {
            return Result.error(CodeMsg.INNER_FAULT.locale());
        }
        return Result.success();
    }

    @GetMapping( "/admin/contest/{contestId}/problem/{num}/delete")
    public String delContestProblem(@PathVariable(value = "contestId",required = true)Integer contestId,
                                          @PathVariable(value = "num",required = true)String num){
        Contest contest = contestMapper.queryAdmin(contestId);
        if (contest == null) {
            return "redirect:/contest/" + contestId;
        }

        if (!contestProblemMapper.delete(contestId, num)) {
            return "redirect:/contest/" + contestId;
        }
        return "redirect:/contest/" + contestId;
    }
}
